import { useState, useMemo } from "react"
import {useLocation} from "react-router-dom"
//此hook用于操作本地存储

type methods = {
    // set: (key: string, value: string) => void;
    set: (value: any) => void;
    // get: () => string | null;
    // rm: (key: string) => void;
    rm: () => void;

}

//key存储到本地的key

//存储到本地的值

/** 
 *@param storageType 存储类型 
 */

 //重新声明全局类型
 declare global {
    interface Window {
    [k: string]: any
    }
 }

// type Istorage = (key: string, value?: string, storageType?: string) => [string | null, methods]
type Istorage = (key: string,storageType?: string) => [string | null, methods]
// const useStorage: Istorage = (key, value, storageType = "localStorage") => {
const useStorage: Istorage = (key, storageType = "localStorage") => {

    //设置localVal初始状态
    // let [localVal, setLocalVAL] = useState<string | null>(null)

    //从本地获取localStorage的值
    // let val = localStorage.getItem(key)
    //使用useMemo从本地取出结果
    let location = useLocation()
    let localVal = useMemo<string | null>(() => {
        // return localStorage.getItem(key)
        let valueRes: string | null;
        try {
            //从本地获取token
            // valueRes = localStorage.getItem(key)
            valueRes = window[storageType].getItem(key)
            valueRes = valueRes ? JSON.parse(valueRes!) : null
            return valueRes
        } catch (e: any) {
            console.log(e);
            return null
        }
    }, [location])
    // setLocalVAL(val)

    //将token存到本地
    // window[storageType].setItem() 
    // let 

    //从本地获取token
    // let get = () => {
    //     let valueRes: string | null;
    //     try {
    //         //从本地获取token
    //         valueRes = localStorage.getItem(key)
    //         valueRes = valueRes ? JSON.parse(valueRes!) : null
    //         return valueRes
    //     } catch (e: any) {
    //         console.log(e);
    //         return null
    //     }
    // }


    //移除token
    // let 

    let methodObj: methods = {
        //设定缓存
        set: (value: any) => {
            let valueJson;
            try {
                valueJson = JSON.stringify(value!)
                // localStorage.setItem(key, valueJson!)
                window[storageType].setItem(key, valueJson!)
            } catch (e: any) {
                console.log(e);
            }
        },
        //移除缓存
        rm: () => {
            // localStorage.removeItem(key)
            window[storageType].removeItem(key)
        }
    } 

    // return [localVal, { set, get, rm }]
    // return [localVal, { set, rm }]
    return [localVal, methodObj]

}

export default useStorage